<template>
  <div id="content">
    <div id="map" ref="map" style="width: 100%;height: 600px;border:1px solid #bfcbd9;padding: 8px;z-index: 0;"></div>
  </div>
</template>

<script>
import "ol/ol.css";
import {Map, Feature, View} from "ol";
import KML from 'ol/format/KML';
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import {Style, Stroke, Icon, Fill, Text} from "ol/style";
import {LineString, Point, Polygon} from "ol/geom";
import XYZ from "ol/source/XYZ";
import {WMTS} from "ol/source";
import {get as getProjection} from "ol/proj";
import {getWidth, getTopLeft} from "ol/extent";

import {
  getTrajectory
} from "@/api/business/researchPlan";
import WMTSTileGrid from "ol/tilegrid/WMTS";

let projection = getProjection("EPSG:4326");
let projectionExtent = projection.getExtent();
let size = getWidth(projectionExtent) / 256;
let key = '8772e5eb459d4047572e31126f708d28' // 这里需要改为你的key值

export default {
  props: {
    researchPlanId: {
      type: Number,
      required: true
    },
  },
  data() {
    return {
      map: null,
      vectorLayer: null,
      trajectoryList: {},
      view: null,
      vectorSource: null,
    };
  },
  created() {
  },
  mounted() {
    this.getTrajectory();
    // this.addKmlLayer();
  },
  methods: {
    getTrajectory() {
      let query = {
        researchPlanId: this.researchPlanId,
        userId: null
      }
      getTrajectory(query).then(res => {
        this.trajectoryList = res.data;
        this.initMap(); //初始化地图
        // if (this.trajectoryList.length > 0) {
        for (let key in this.trajectoryList) {
          let tData = this.trajectoryList[key];
          console.log('-----tData----', tData);
          this.addTrack(key, tData); //创建
        }
        // }
      });
    },
    addTrack(name, trajectoryList) {
      for (let dIndex in trajectoryList) {
        let data = trajectoryList[dIndex];
        data[0] = Number(data[0])
        data[1] = Number(data[1])
      }
      // 根据经纬度点位创建线
      let routeFeature = new Feature({
        type: "route",
        geometry: new LineString(trajectoryList),
      });
      // 创建开始图标
      const startMarker = new Feature({
        type: "startMarker",
        geometry: new Point(trajectoryList[0]),
      });
      // 创建结束图标
      const endMarker = new Feature({
        type: "endMarker",
        geometry: new Point(trajectoryList[trajectoryList.length - 1]),
      });
      // 设置样式
      let styles = {
        // 如果类型是 route 的样式
        route: new Style({
          stroke: new Stroke({
            width: 2, //线的宽度
            color: "#ffc641", //线的颜色
          }),
          text: new Text({
            font: '13px Microsoft YaHei',
            text: name,
            textAlign: "left",
            fill: new Fill({
              color: '#666'
            }),
            stroke: new Stroke({
              color: '#f2f',
              width: 1
            })
          })
        }),
        // 如果类型是 geoMarker 的样式
        startMarker: new Style({
          image: new Icon({
            src: require("../../../assets/images/start.png"),
            anchor: [0.5, 1.1], // 设置偏移
          }),
        }),
        endMarker: new Style({
          image: new Icon({
            src: require("../../../assets/images/end.png"),
            anchor: [0.5, 1.1], // 设置偏移
          }),
        }),
      };
      // 把小车和线添加到图层
      this.vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: [routeFeature, startMarker, endMarker],
        }), //线,起点的图标,终点的图标
        style: function (feature) {
          return styles[feature.get("type")];
        },
        zIndex: 3
      });
      this.map.addLayer(this.vectorLayer);
      this.map.getView()
        .fit(new Polygon([trajectoryList]), {
          padding: [10, 10, 10, 10],
        }); //设置地图的缩放距离离屏幕的大小
    },
    /**
     * 初始化一个 openlayers 地图
     */
    initMap() {
      const target = "map"; // 跟页面元素的 id 绑定来进行渲染
      let TiandiMap_img = new TileLayer({
        name: '天地图影像图层',
        visible: true,
        source: new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=8772e5eb459d4047572e31126f708d28',
          wrapX: false,
        }),
        zIndex: 1
      });
      let TiandiMap_imgcia = new TileLayer({
        name: '天地图影像注记图层',
        visible: true,
        source: new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=8772e5eb459d4047572e31126f708d28',
          wrapX: false,
        }),
        zIndex: 2
      });
      // 渲染地图

      const tileLayer = [
        // TiandiMap_img, TiandiMap_imgcia
        ...this.img_c()
      ];
      this.view = new View({
        center: [116.23128, 40.22077],
        projection: projection,
        zoom: 8,
        maxZoom: 17,
        minZoom: 1,
        enableRotation: false,
      })
      this.map = new Map({
        target: target, // 绑定dom元素进行渲染
        layers: tileLayer, // 配置地图数据源
        view: this.view
      });
    },
    addKmlLayer() {
      let styles = new Style({
        fill: new Fill({
          color: 'rgba(245, 0, 255, 0.5)'
        }),
        stroke: new Stroke({
          color: '#ffcc33',
          width: 10
        })
      });
      let vectorSource2 = new VectorSource({
        url: 'map1.kml', // 这个地址是从public文件夹中读取
        format: new KML({
          // dataProjection: 'EPSG:4326',
          // featureProjection: 'EPSG:3857',
          extractStyles: false //至关重要
        }),
        // projection: 'EPSG:3857'
      });
      let kmlLayer = new VectorLayer({
        source: vectorSource2,
        style: styles,
        zIndex: 100
      });
      this.map.addLayer(kmlLayer);
    },
    getResolutions() {
      let resolutions = [];
      for (let z = 1; z < 20; ++z) {
        resolutions[z] = size / Math.pow(2, z);
      }
      return resolutions

    },
    // WMTS 形式
    getWMTSLayer(url, layer) {
      return new TileLayer({
        source: new WMTS({
          name: "中国",
          url: url,
          layer: layer,
          style: "default",
          matrixSet: "c",
          format: "tiles",
          wrapX: true,
          tileGrid: new WMTSTileGrid({
            origin: getTopLeft(projectionExtent),
            resolutions: this.getResolutions(),
            matrixIds: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
          }),
        }),
      })
    },
    /**
     * 矢量底图 + 矢量注记
     */
    vec_c() {
      return [
        this.getWMTSLayer('http://t{0-7}.tianditu.gov.cn/vec_c/wmts?tk=' + key, 'vec'),
        this.getWMTSLayer('http://t{0-7}.tianditu.gov.cn/cva_c/wmts?tk=' + key, 'cva')
      ]
    },
    /**
     * 影像底图 + 影像注记
     */
    img_c() {
      return [
        this.getWMTSLayer('http://t{0-7}.tianditu.gov.cn/img_c/wmts?tk=' + key, 'img'),
        this.getWMTSLayer('http://t{0-7}.tianditu.gov.cn/cia_c/wmts?tk=' + key, 'cia')
      ]
    }
  }
};
</script>
<style lang="scss" scoped>

</style>
